<?php
namespace Org;

/**
 * PHP 实现的 AES对称加密算法
 * AES加密算法即密码学中的高级加密标准（Advanced Encryption Standard，AES），
 * 又称Rijndael加密法，是美国联邦政府采用的一种区块加密标准。
 * 这个标准用来替代原先的DES，已经被多方分析且广为全世界所使用。
 * 经过五年的甄选流程，高级加密标准由美国国家标准与技术研究院 （NIST）
 * 于2001年11月26日发布于FIPS PUB 197，并在2002年5月26日成为有效的标准。
 * @author leeyi <leeyisoft@qq.com>
 * @description
 *    public function javaAES() {
 *        $m = new \Org\AESEncrypt();
 *        $m->setKey('1q2w3e4r*🐶');
 *        $m->requirePkcs5();
 *        $m->setMode('cbc');
 *        $m->setIv('abc2030405060708');
 *        $x = "inPRk2JiGIGSPAY1PsoLoA==";
 *        $y = $m->decrypt($x);
 *        $z = $m->encrypt('等等hh🐷');
 *        var_dump($x, $y, $z);
 *    }
 *
 *  public function objCAES() {
 *        $m = new \Org\AESEncrypt();
 *        $m->setKey('1q2w3e4r*🐶');
 *        $m->requirePkcs5();
 *        $m->setMode('cbc');
 *        $m->setIv('abc2030405060708');
 *        $x = "MSVbpcJlzq/HqcpSoHA4SA";
 *        $y = $m->decrypt($x);
 *        $z = $m->encrypt('等等hh🐷');
 *        var_dump($x, $y, $z);
 *    }
 */

class AESEncrypt {
    protected $cipher = MCRYPT_RIJNDAEL_128;
    protected $mode = MCRYPT_MODE_ECB;
    protected $pad_method = NULL;
    protected $secret_key = '';
    protected $iv = ''; // Java版本的iv必须是16位字符串，所以这里要一直
 
    public function setCipher($cipher) {
        $this->cipher = $cipher;
    }
 
    public function setMode($mode) {
        $this->mode = $mode;
    }
 
    public function setIv($iv) {
        $this->iv = $iv;
    }
 
    public function setKey($key) {
        $this->secret_key = $key;
    }
 
    public function requirePkcs5() {
        $this->pad_method = 'pkcs5';
    }

    public function requirePkcs7() {
        $this->pad_method = 'pkcs7';
    }

    protected function padOrUnpad($str, $ext) {
        if ( is_null($this->pad_method) ) {
            return $str;
        } else {
            $func_name = __CLASS__ . '::' . $this->pad_method. $ext . 'Pad';
            if ( is_callable($func_name) ) {
                $size = mcrypt_get_block_size($this->cipher, $this->mode);
                return call_user_func($func_name, $str, $size);
            }
        }
        return $str;
    }
 
    protected function pad($str) {
        return $this->padOrUnpad($str, '');
    }
 
    protected function unpad($str) {
        return $this->padOrUnpad($str, 'Un');
    }
 
    public function encrypt($str) {
        $str = $this->pad($str);
        $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
        if ( empty($this->iv) ) {
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        } else {
            $iv = $this->iv;
        }
        mcrypt_generic_init($td, $this->secret_key, $iv);
        $cyper_text = mcrypt_generic($td, $str);
        $rt=base64_encode($cyper_text);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
 
        return $rt;
    }
 
    public function decrypt($str) {
        $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
 
        if( empty($this->iv) ) {
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        } else {
            $iv = $this->iv;
        }
 
        mcrypt_generic_init($td, $this->secret_key, $iv);

        $decrypted_text = mdecrypt_generic($td, base64_decode($str));
        $rt = $decrypted_text;
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $rt=rtrim($rt,"\0");//解密出来的数据后面会出现如图所示的六个红点；这句代码可以处理掉，从而不影响进一步的数据操作
        return $this->unpad($rt);
    }
 
    public static function hex2bin($hexdata) {
        $bindata = '';
        $length = strlen($hexdata);
        for ($i=0; $i < $length; $i += 2) {
            $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
        }
        return $bindata;
    }
 
    public static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
 
    public static function pkcs5UnPad($text) {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
        return substr($text, 0, -1 * $pad);
    }

    public function pkcs7Pad($data, $blocksize) {
        $padding = $blocksize - strlen($data) % $blocksize;
        $padding_text = str_repeat(chr($padding), $padding);
        return $data . $padding_text;
    }
    public function pkcs7UnPad($data) {
        $length = strlen($data);
        $unpadding = ord($data[$length - 1]);
        return substr($data, 0, $length - $unpadding);
    }
}
